package com.yuke.cloud.service.omc.redis;

import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.service.omc.dto.SecKillOrderDto;
import com.yuke.cloud.service.omc.entity.OdsShopCart;
import com.yuke.cloud.service.omc.service.OdsShopCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 消费者
 * @author
 */
@Service
public class RedisConsumer {
	
	@Autowired
	private OdsShopCartService odsShopCartService;

	/**
	 *
	 * @param message 内容为Json对象的字符串
	 */
    public void receiveMessage(String message) {
        //收到通道的消息之后执行秒杀操作(超卖)
		SecKillOrderDto secKillOrderDto = (SecKillOrderDto)JSONObject.parse(message);

		// 将商品添加到购物车中
		// 先判断购物车中是否有该商品
		Example example = new Example(OdsShopCart.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", secKillOrderDto.getUserId());
		criteria.andEqualTo("shopId", secKillOrderDto.getShopId());
		criteria.andEqualTo("specId", secKillOrderDto.getSpecId());
		List<OdsShopCart> odsShopCartList = odsShopCartService.selectByExample(example);
		if (odsShopCartList == null && odsShopCartList.size() > 0) {  // 更新
			OdsShopCart odsShopCart = odsShopCartList.get(0);

			Integer count = secKillOrderDto.getNum() + odsShopCart.getNum();
			odsShopCart.setNum(count);
			odsShopCartService.update(odsShopCart);
		} else {  // 增加
			OdsShopCart odsShopCart = new OdsShopCart();
			BeanUtils.copyProperties(secKillOrderDto, odsShopCart);
			odsShopCartService.save(odsShopCart);
		}
    }
}